package masterjava.common.convertion;

import masterjava.common.logging.ServerLogger;
import masterjava.common.shared.Convertible;
import org.springframework.core.convert.converter.Converter;

/**
 * User: GKislin
 * Date: 20.02.2011
 */
public class GenericStringConverter<T> implements Convertible<T>, Converter<String, T> {
    protected static final ServerLogger LOGGER = ServerLogger.get(GenericStringConverter.class);
    protected final Class<T> clazz;

    public GenericStringConverter(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public T toValue(String property) {
        try {
            return ConverterUtils.toValue(property, clazz);
        } catch (Exception e) {
            throw LOGGER.getIllegalArgumentException(property + " coudn't be converted", e);
        }
    }

    @Override
    public String toString(T value) {
        return value == null ? null : value.toString();
    }

    @Override
    public T convert(String source) {
        return toValue(source);
    }
}
